
  -- SELECT TOP 10 * FROM SERVER16.[VPB_WHR2].[DBO].[TBL_LIMIT_ORG] --EXPRIRY_DATE(HOP DONG HAN MUC)
  --SELECT TOP 10 * FROM SERVER74.STAGING.[DBO].[DLYTB_LIMIT_ORG] 
  IF EXISTS(SELECT *
         FROM DBO.SYSOBJECTS O
        WHERE O.XTYPE IN ('U') AND O.NAME = 'LIMIT_EXPIRY_RAW')
  DROP TABLE LIMIT_EXPIRY_RAW
  
declare @date_update nvarchar(100)= (select [DATE_UPDATE] from [DATE_EM_REPORT])
declare @date_last_month nvarchar(100)= (SELECT DATEADD(m,2,CONVERT(date,@date_update)) )

  SELECT BUSINESS_DATE, [ID], APPROVAL_DATE, EXPIRY_DATE, INTERNAL_AMOUNT, LIABILITY_NUMBER, CO_CODE,ONLINE_LIMIT
  INTO LIMIT_EXPIRY_RAW
  FROM SERVER74.STAGING.[DBO].[DLYTB_LIMIT_ORG] 
  WHERE EXPIRY_DATE BETWEEN @date_update AND @date_last_month AND LIABILITY_NUMBER IN (SELECT CIF FROM TBL_CUSTOMER)

  --SELECT * FROM LIMIT_EXPIRY_RAW
    IF EXISTS(SELECT *
         FROM DBO.SYSOBJECTS O
        WHERE O.XTYPE IN ('U') AND O.NAME = 'TBL_CM_ALERT_LIMIT')
  DROP TABLE TBL_CM_ALERT_LIMIT

  SELECT A.BUSINESS_DATE, ID, APPROVAL_DATE, EXPIRY_DATE, C.BRANCH_ID,(CASE WHEN INTERNAL_AMOUNT LIKE'%B%'THEN REPLACE(INTERNAL_AMOUNT,'B','000000000')
		WHEN INTERNAL_AMOUNT LIKE'%M%'THEN REPLACE(INTERNAL_AMOUNT,'M','000000') 
		ELSE INTERNAL_AMOUNT END)AS INTERNAL_AMOUNT_QD , C.BRANCH_CODE_SME, C.BRANCH_NAME_SME, B.DAO_NAME, B.DAO , LIABILITY_NUMBER AS CIF, C.REGION, B.CUS_NAME, B.INDUSTRY_NAME, B.INDUSTRY_NAME_EN
		INTO TBL_CM_ALERT_LIMIT
		FROM LIMIT_EXPIRY_RAW A, TBL_CUSTOMER B, TBL_BRANCH C
		WHERE (ID LIKE '%0050000%') AND A.LIABILITY_NUMBER = B.CIF AND B.BRANCH_ID= C.BRANCH_ID
		ORDER BY LIABILITY_NUMBER

		
update b
set b.date_data = a.BUSINESS_DATE
from (select max(business_date) as BUSINESS_DATE from TBL_CM_ALERT_LIMIT) a,  TBL_DATE_BUSINESS b
where b.name_table = 'TBL_CM_ALERT_LIMIT'
-- DELETE FROM [DBCUSTOMER].DBO.TBL_CM_ALERT_LIMIT
--INSERT INTO [DBCUSTOMER].DBO.TBL_CM_ALERT_LIMIT
--SELECT * FROM TBL_CM_ALERT_LIMIT

-- EXEC('IF EXISTS
--      (SELECT *
--         FROM [SERVER12].[SMECUSTOMER360].DBO.SYSOBJECTS O
--        WHERE O.XTYPE IN (''U'') AND O.NAME = ''TBL_CM_ALERT_LIMIT'')
--        DELETE FROM [SERVER12].[SMECUSTOMER360].DBO.TBL_CM_ALERT_LIMIT')
 
--INSERT [SERVER12].[SMECUSTOMER360].DBO.TBL_CM_ALERT_LIMIT
--SELECT * FROM TBL_CM_ALERT_LIMIT